package utils

import (
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"shorturl/log"
)

type Response struct {
	Status      string  `json:"status"`
	Country     string  `json:"country"`
	CountryCode string  `json:"countryCode"`
	Region      string  `json:"region"`
	RegionName  string  `json:"regionName"`
	City        string  `json:"city"`
	Zip         string  `json:"zip"`
	Lat         float64 `json:"lat"`
	Lon         float64 `json:"lon"`
	Timezone    string  `json:"timezone"`
	Isp         string  `json:"isp"`
	Org         string  `json:"org"`
	As          string  `json:"as"`
	Query       string  `json:"query"`
}

func GetIpInfo(ip string) (*Response, error) {
	url := fmt.Sprintf("http://ip-api.com/json/%s?lang=zh-CN", ip)
	resp, err := http.Get(url)
	if err != nil {
		log.Logger.Error("获取IP信息失败", zap.Error(err))
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Logger.Error("读取响应体失败", zap.Error(err))
		return nil, err
	}

	var response Response

	if err := json.Unmarshal(body, &response); err != nil {
		log.Logger.Error("解析响应体失败", zap.Error(err))
		return nil, err
	}

	//fmt.Println(resp)

	if response.Status != "success" {
		log.Logger.Error("查询失败")
		return nil, fmt.Errorf("query failed")
	}

	return &response, nil
}
